/*
 * $Id: Picture.java 101 2009-04-30 14:06:55Z meyer@alphatec.de $
 * 
 *
 * Copyright 2009 DeltaDesk
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package deltadesk.gui.deltagui.widget;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

import deltadesk.gui.deltagui.graphics.GraphicsUtil;

/**
 * Picture.
 * 
 * @author Andreas Meyer
 * @version $Revision: 101 $
 */
public class Picture extends Control {

	/** The image to draw. */
	private transient BufferedImage image;

	/** The scaled image. */
	private transient BufferedImage scaledImage;

	/** Error state. */
	private transient boolean error;
	
	/** The URL. */
	private URL source;
	
	/** Thread pool for image loading. */
	private static final ThreadPoolExecutor tpe;
	
	
	static {

		//TODO: use central picture loader
		tpe = new ThreadPoolExecutor(1,   // core pool size
				                     10,  // max pool size
				                     300, // keep alive time 
				                     TimeUnit.SECONDS,
				                     new ArrayBlockingQueue<Runnable>(100));
	}

	/**
	 * Construct the picture.
	 * 
	 * @param urlStr
	 * @throws MalformedURLException
	 */
	public Picture(final String urlStr) throws MalformedURLException {
		this(new URL(urlStr));
	}

	/**
	 * Construct the picture.
	 * 
	 * @param url
	 */
	public Picture(final URL url) {
		
		setSource(url);
	}

	/**
	 * @see deltadesk.gui.deltagui.widget.Control#onDeactivate()
	 */
	@Override
	protected void onDeactivate() {
		
		//TODO: Only for last visible picture
		if (!tpe.isShutdown()) {
			tpe.shutdownNow();
		}
	}

	/**
	 * @see deltadesk.gui.deltagui.widget.Widget#onResize()
	 */
	@Override
	protected void onResize() {
		update();
	}

	/**
	 * @see deltadesk.gui.deltagui.widget.Control#renderControl(java.awt.Graphics2D)
	 */
	@Override
	public void renderControl(final Graphics2D g2) {

		if(error) {
			
			g2.drawString("Error", 10, 15);
			return;
		}

		if(scaledImage != null) {
			g2.drawImage(scaledImage, 0, 0, null);
		}
	}

	/**
	 * Set the source of the image.
	 * 
	 * @param source
	 */
	public void setSource(final URL source) {
		
		if(source == null || source.equals(this.source)) {
			return;
		}
		
		this.source = source;

		scaledImage = null;
		error = false;
		setUnrendered();

		// load image delayed
		tpe.execute(new Runnable() {

			public void run() {

				try {
					
					image = ImageIO.read(source);
					if(image != null) {
						setPreferredSize(image.getWidth(), image.getHeight());
					} else {
						error = true;
						setUnrendered();
					}
					invalidate();
				} catch (IOException e) {
					error = true;
				}
			}
			
		});
	}

	/**
	 * Update the scaled image
	 */
	private void update() {

		if (image != null && getWidth() > 0 && getHeight() > 0) {

			scaledImage = GraphicsUtil.resize(image, getWidth(), getHeight(), false);
			setUnrendered();
		}
	}

}
